package pcloud.client.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import org.entityfs.support.log.LogAdapterHolder;
import org.entityfs.support.log.StdOutLogAdapter;
import org.entityfs.util.io.ReadWritableFileAdapter;
import org.helidb.Database;
import org.helidb.backend.heap.HeapBackendBuilder;
import org.helidb.impl.simple.SimpleDatabase;
import org.helidb.lang.serializer.StringSerializer;

public class KeyValueDB<V> implements TreeDB<V>
{
	// A LogAdapter that logs to stdout and stderr.
	LogAdapterHolder lah = 
	  new LogAdapterHolder(
	    new StdOutLogAdapter());

	Database<String, String> db = 
	  new SimpleDatabase<String, String, Long>(
	    // Use a HeapBackendBuilder object to build the HeapBackend.
	    // Objects in HeliDB with many configurable parameters often have builder 
	    // objects to make it easier to construct them.
	    new HeapBackendBuilder<String, String>().
	      setKeySerializer(StringSerializer.INSTANCE).
	      setValueSerializer(StringSerializer.INSTANCE).
	      // Adapt the File to a ReadWritableFile.
	      create(new ReadWritableFileAdapter(
	    		  new File("D:\\WatchDB\\PCloudClient.db"))),
	    		  lah);
	
	public boolean contains(String key)
	{
		return db.containsKey(key);
	}

	@SuppressWarnings("unchecked")
	public V get(String key)
	{
		String valueString = db.get(key);
		ByteArrayInputStream serializedArray = new ByteArrayInputStream(valueString.getBytes());
		try {
			ObjectInputStream serializeStream = new ObjectInputStream(serializedArray);
			Object valueObj = serializeStream.readObject();
			serializeStream.close();
			
			return (V)valueObj;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		return null;
	}

	public List<V> getChild(String arg0)
	{
		// TODO Auto-generated method stub
		return null;
	}

	public V put(String key, V value)
	{
		ByteArrayOutputStream serializedArray = new ByteArrayOutputStream();
		try {
			ObjectOutputStream serializeStream = new ObjectOutputStream(serializedArray);
			serializeStream.writeObject(value);
			serializeStream.close();
			
			String valueString = serializedArray.toString();
			db.put(key.toString(), valueString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		//(new StringOutputStream("D:""objectFile.obj"));
		
		return null;
	}

	
}
